/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uit.ieproject.utilites;

import java.awt.Component;
import java.awt.Desktop;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

import jvntokenizer.PennTokenizer;
import org.json.JSONException;
import org.json.JSONObject;
import uit.ieproject.business.RegexBLO;
import uit.ieproject.entities.Regex;

/**
 *
 * @author Maivia
 */
public class FileUtil {

    public static final String path = "\\src\\uit\\ieproject\\";
    public static JFileChooser chooser = new JFileChooser();

    public static ArrayList<File> getFiles(String type, boolean isMultiSelection) {
        ArrayList<File> files = new ArrayList<>();
        chooser.setMultiSelectionEnabled(isMultiSelection);
        chooser.setFileFilter(new TextFilter(type)); //Cong
        int r = chooser.showOpenDialog(new JFrame());
        if (r == JFileChooser.APPROVE_OPTION) {
            if (isMultiSelection == true) {
                File[] temp = chooser.getSelectedFiles();
                if (temp.length > 0) {
                    files.addAll(Arrays.asList(temp));
                }
            } else {
                File temp = chooser.getSelectedFile();
                files.add(temp);
            }
        }
        return files;
    }

    public static void openFile(File file) {
        try {
            boolean desktopSupported;
            //checking that the current system supports the awt Desktop class
            desktopSupported = Desktop.isDesktopSupported();
            if (desktopSupported) {
                Desktop.getDesktop().open(file);
            } else {
            }
        } catch (Exception ex) {
        }
    }

    //trả về thư mục chưa file hình ảnh
    public static File getCurrentDir(String filename, String typeImage) throws IOException {
        File currentDirectory = new File(new File(".").getCanonicalPath() + path + "character\\" + filename + "." + typeImage);
        return currentDirectory;
    }

    //download và lưu file
    public static void saveUrl(String filename, String typeImage) throws MalformedURLException, IOException {
        try {
            String UrlImage = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=";
            URL url = new URL(UrlImage + URLEncoder.encode(filename, "UTF-8"));
            //System.out.println(URLEncoder.encode(filename, "UTF-8"));

            URLConnection connection = url.openConnection();

            String line;
            StringBuilder builder = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }

            JSONObject json = new JSONObject(builder.toString());
            String imageUrl = json.getJSONObject("responseData").getJSONArray("results").getJSONObject(0).getString("url");

            File currentDirectory = getCurrentDir(filename, typeImage);

            BufferedImage imagedownload = ImageIO.read(new URL(imageUrl));
            ImageIO.write(imagedownload, typeImage, currentDirectory);
        } catch (IOException | JSONException e) {
        }
    }

    public static void saveFile(boolean isProjectDir, String specifyDirTo, File fromFile, String name, String type) throws IOException {
        File dtFile;
        if (isProjectDir == true) {
            dtFile = new File(new File(".").getCanonicalPath() + path + "character\\" + name + "." + type);
        } else {
            dtFile = new File(specifyDirTo + name + "." + type);
        }
        if (!dtFile.exists()) {
            dtFile.createNewFile();
        }
        try {
            InputStream in = new FileInputStream(fromFile);

            OutputStream out = new FileOutputStream(dtFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        } catch (IOException ex) {
        }
    }

    public static ArrayList<String> senTokenize(File inputFile) {
        ArrayList<String> results = new ArrayList<>();
        StringBuilder content = new StringBuilder();
        String name = "";
        try {
            BufferedReader reader;
            RegexBLO regexBLO = new RegexBLO();
            ArrayList<Regex> regexs = regexBLO.getRegex("Năm sinh", "Rút trích", 1);
            int numRegexs = regexs.size();
            if (numRegexs > 0) {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8"));
                String line;
                int numLine = 1;
                while ((line = reader.readLine()) != null) {
                    String formatLine = PennTokenizer.tokenize(line);
                    if (numLine == 1) {
                        for (int i = 0; i < numRegexs; i++) {
                            Pattern pattern = Pattern.compile(regexs.get(i).getExpression());
                            Matcher matcher = pattern.matcher(formatLine);
                            while (matcher.find()) {
                                name = matcher.group("name").trim();
                                break;
                            }
                        }
                    }
                    content.append(line);
                    content.append("\n");
                    numLine++;
                }
                reader.close();
            }
        } catch (IOException | SQLException ex) {
        }
        results.add(content.toString());
        results.add(name);
        return results;
    }

    //get the extension of file
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf(".");
        if (i > 0 && i < s.length() - 1) {
            ext = s.substring(i + 1).toLowerCase();
        }
        return ext;
    }

    public static String promptForFolder(Component parent) {
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setFileFilter(new TextFilter("txt"));

        if (fc.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
            return fc.getSelectedFile().getAbsolutePath();
        }
        return null;
    }

    public static Long[] convertToLongArray(int[] array) {
        Long[] result = new Long[array.length];
        for (int i = 0; i < array.length; i++) {
            result[i] = Long.valueOf(array[i]);
        }
        return result;
    }

    public static File saveTextToFile(String root, String name, String type, ArrayList<String> list, boolean append) throws IOException {
        BufferedWriter writer = null;
        File file = new File(root + name + "." + type);
        try {
            file.createNewFile();
            writer = new BufferedWriter(new FileWriter(file, append));
            for (int i = 0; i < list.size(); i++) {
                writer.write(list.get(i).toString());
                writer.write("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static File getImageFromPath(String name, String path, String typeImage) {
        File fileImage;
        try {
            String strImage = path.substring(0, path.length() - 3) + typeImage;
            fileImage = new File(strImage);
            if (fileImage.exists()) {
                return fileImage;
            }
        } catch (Exception ex) {
        }
        return null;
    }
}
